const util = require("../utils/connection");
const Table = require("../utils/table");
const TableUtil = new Table(
  "article",
  [
    "id",
    "uid",
    "title",
    "content",
    "outline",
    "cover",
    "state",
    "create_time",
    "update_time"
  ],
  {
    updateFilterField: ["create_time", "tags"],
    insertFilterField: "tags"
  }
);
const userService = require("./user");
const tagService = require("./tag");
const $date = require("../utils/date");

const articleQueryField = ["title", "state"]; // 对象本身的查询字段

/**
 * 根据ID查询文章数量
 * @param connection 需要提供一个连接对象
 * @param {Object} query 查询条件
 * @return {Promise<any>}
 * @private
 */
function _selectCountById(connection, query) {
  return new Promise(resolve => {
    let sql = "select count(id) from article where 1 = 1";
    for (const value of articleQueryField) {
      if (!query[value]) continue;
      sql += ` and ${value} = '${query[value]}'`;
    }
    connection.query(sql, function(error, results) {
      if (error) throw error;
      resolve(results[0]["count(id)"]);
    });
  });
}

module.exports = {
  /**
   * 根据ID查询文章
   * @param {Number} id 文章ID
   */
  selectById: function(id) {
    return new Promise(async resolve => {
      const sql =
        "select id, uid, title, content, outline, cover, state, create_time, update_time from article where id = ?";
      const connection = await util.getConnection();
      connection.query(sql, [id], async function(error, results) {
        connection.release();
        if (error) throw error;
        const article = results[0];
        if (results[0]) {
          const u = await userService.getUserById(results[0].uid);
          article["author"] = u.data.username;
        }
        resolve({ data: article || {} });
      });
    });
  },
  /**
   * 分页查询
   * @param {Object} query 分页查询对象
   * @param {Number} query.currentPage 当前页
   * @param {Number} query.pageSize 每页长度
   * @param {Boolean} isWeb 是否是给web端用的
   * @return {Promise<any>}
   */
  selectByPage: function(query, isWeb) {
    return new Promise(async resolve => {
      const connection = await util.getConnection();
      let sql =
        "select " +
        "a.id id, uid, title, content, outline, cover, state, update_time, create_time, " +
        "username author from article a left join user u on a.uid = u.id where 1 = 1";
      for (const value of articleQueryField) {
        if (!query[value]) continue;
        sql += ` and ${value} = '${query[value]}'`;
      }
      sql += ` order by update_time desc limit ${(query["currentPage"] - 1) *
        query["pageSize"]}, ${query["pageSize"]}`;
      connection.query(sql, async function(err, results) {
        if (err) {
          connection.release();
          throw err;
        }
        const total = await _selectCountById(
          connection,
          isWeb ? { state: "publish" } : {}
        );
        const list = results || [];
        connection.release();
        resolve({ data: { rows: list, total } });
      });
    });
  },
  /**
   * 修改或保存文章
   * @param article
   */
  insertOrUpdate: async function(article) {
    const now = $date.format(new Date());
    article["update_time"] = now;
    if (!article.id) article["create_time"] = now;
    const articleRep = await TableUtil.insertOrUpdate(article);
    let aId = article.id; // 文章ID
    if (articleRep.id) aId = articleRep.id;
    // 1.循环tags，查看是否有新增记录，tag需要是一个对象
    for (const tag of article.tags) {
      // let tId = tag.id;
      await tagService
        .insertOrUpdate(tag)
        .then(({ id }) => {
          console.log("插入id正常，id是：" + id);
          // if (id) tId = id;
        })
        .catch(error => {
          console.error("插入tag产生了异常", error.message);
        });
    }
    return articleRep;
  }
};
